package main

import (
	"DomCtrlCenter/data"
	"DomCtrlCenter/model"
	"fmt"
	"html/template"
	"net/http"
	"reflect"
	"runtime"
)

func EasyHttpServer() {
	server := http.Server{
		Addr: "127.0.0.1:8081",
	}
	http.HandleFunc("/process", process)
	http.HandleFunc("/write", writeExample)
	http.HandleFunc("/writeheader", writeHeaderExample)
	http.HandleFunc("/redirect", headerExample)
	server.ListenAndServe()
}
func getCookie(w http.ResponseWriter, r *http.Request) {
	h := r.Header["Cookie"]
	h2, _ := r.Cookie("name")
	//cs := r.Cookies()  = r.Header["Cookie"]
	fmt.Fprintln(w, h, h2)
}
func writeExample(w http.ResponseWriter, r *http.Request) {
	str := "<html></html>"
	w.Write([]byte(str))
}
func writeHeaderExample(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(501)
	fmt.Fprintf(w, "No such service")
}
func headerExample(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Location", "http://baidu.com")
	w.WriteHeader(302) //与前一句顺序不能颠倒
}
func process(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	fmt.Fprintln(w, r.Form)
}

func log(h http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		name := runtime.FuncForPC(reflect.ValueOf(h).Pointer()).Name()
		fmt.Println("Handler function called: " + name)
		h(w, r)
	}
}
func handler(writer http.ResponseWriter, request *http.Request) {
	fmt.Fprintf(writer, "Hello, %s\n", request.URL.Path[1:])
}

func authenticate(writer http.ResponseWriter, request *http.Request) {
	request.ParseForm()
	user := request.PostFormValue("user")
	passwd := request.PostFormValue("passwd")
	session := data.CreateSessionByUser(user)
	if user == "kaede" && passwd == "123356" {
		cookie := http.Cookie{
			Name:     "_cookie",
			Value:    session.Uuid,
			HttpOnly: true,
		}
		http.SetCookie(writer, &cookie)
		http.Redirect(writer, request, "/", 302)
	} else {
		http.Redirect(writer, request, "/login", 302)
	}
}

func HTMLServer() {
	mux := http.NewServeMux()
	files := http.FileServer(http.Dir("./public"))
	mux.Handle("/static/", http.StripPrefix("/static/", files))
	mux.HandleFunc("/aircon/set", model.HandleSetAirconRequest)
	mux.HandleFunc("/aircon/timer/set", model.HandleSetAirconTimerRequest)
	mux.HandleFunc("/", log(index))
	server := &http.Server{
		Addr:    "0.0.0.0:8081",
		Handler: mux,
	}
	server.ListenAndServe()
}

func index(writer http.ResponseWriter, request *http.Request) {
	_, err := session(writer, request)
	guestFiles := []string{"panel"}
	adminFiles := []string{"panel"}
	fmt.Println(err)
	if err == nil {
		generateHTML(writer, nil, adminFiles...)
	} else {
		generateHTML(writer, model.AirGetStatus(), guestFiles...)
	}
}

func generateHTML(w http.ResponseWriter, data any, fn ...string) {
	var files []string
	for _, file := range fn {
		files = append(files, fmt.Sprintf("templates/%s.html", file))
	}
	templates := template.Must(template.ParseFiles(files...))
	//templates.Execute(w, data)
	templates.ExecuteTemplate(w, "panel", data)
}
